package com.jlnk.retrofitdemo.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.jlnk.retrofitdemo.R;
import com.jlnk.retrofitdemo.response.HotNewsResponse;

import java.util.List;

public class HotSearchAdapter extends RecyclerView.Adapter<HotSearchAdapter.ViewHolder> {
    private Context context;
    private List<HotNewsResponse.Result> data;

    public HotSearchAdapter(Context context, List<HotNewsResponse.Result> data) {
        this.context = context;
        this.data = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_hot_search, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        HotNewsResponse.Result item = data.get(position);
        holder.textIndex.setText(context.getString(R.string.format_index, item.getTitle()));
        holder.textTitle.setText(item.getTitle());

        holder.itemView.setOnClickListener(v -> {
            if (item.getLink() != null && !item.getLink().isEmpty()) {
                context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(item.getLink())));
            }
        });
    }

    public void updateData(List<HotNewsResponse.Result> newData) {
        this.data = newData;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textIndex;
        TextView textTitle;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textIndex = itemView.findViewById(R.id.text_index);
            textTitle = itemView.findViewById(R.id.text_title);
        }
    }
}